package com.jackrain.nea.omslocal.util;

import com.alibaba.fastjson.JSONObject;
import com.jackrain.nea.util.Validator;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.FastDateFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.util.Date;
import java.util.Set;

/**
 * @Discription: 将传入的 json 打包,构造 sql 语句, key 为字段, value 为值
 * Created with IntelliJ IDEA.
 * @Author cs
 * @Date 2018/5/3 14:26
 */
@Component
@Slf4j
public class PackageJsonSqlUtil {

    @Autowired
    private RegexDateUtil regexDate;
    private FastDateFormat fastformat = FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss");

    /**
     * 获取新增 keys
     * @param jsonObj
     * @return
     */
    public String packageInsertCloumnName(JSONObject jsonObj) {

        String columnName = "";
        Set set = jsonObj.keySet();
        for (Object obj1 : set) {
            columnName = columnName + "," + obj1;
        }
        columnName = columnName.substring(1);
        return columnName;
    }

    /**
     * 获取新增 values
     * @param objArr
     * @return
     */
    public String packageInsertColumnValue(Object[] objArr) throws ParseException {

        String columnValue = "";
        for (int i = 0; i < objArr.length; i++) {

            if (objArr[i] instanceof String) {
                if (regexDate.regexDate(((String) objArr[i]))) {
                    Date date = fastformat.parse(((String) objArr[i]));
                    objArr[i] = date;
                }
            }
            columnValue = columnValue + ",?";
        }

        columnValue = columnValue.substring(1);
        return columnValue;
    }


    /**
     * 获取修改 参数
     * @param jsonObj
     * @return
     */
    public String packageUpdateCloumnName(JSONObject jsonObj) {

        String params = "";
        Set set = jsonObj.keySet();
        for (Object obj1 : set) {
            Object tempobject = jsonObj.get(obj1);
            params = params + "" + obj1 + " = ?,";
        }
        params = params.substring(0, params.length() - 1);
        return params;
    }

    /**
     * 校验 修改数据 参数 是否为空, 是否是 date 类型
     * @param jsonObject
     * @return
     */
    public Object[] packageUpdateColumnValue(JSONObject jsonObject) throws ParseException {

        Object[] objArr = jsonObject.values().toArray();
        for (int i = 0; i < objArr.length; i++) {

            if (Validator.isNull(objArr[i])) {
                objArr[i] = "null";
            }
            if (objArr[i] instanceof String) {
                if (regexDate.regexDate(((String) objArr[i]))) {
                    Date date2 = fastformat.parse(((String) objArr[i]));
                    objArr[i] = date2;
                }
            }
        }

        return objArr;
    }

}
